<template>
  <div class="login">
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username" ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pwd">
        <el-input  type="password" v-model="ruleForm.pwd" ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import UserHttp from '@/models/User'
export default {
  name: 'Home',
  data() {
     var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('密码不能为空'));
        }else{
          if(value.length<6){
            callback(new Error('密码长度不能小于6'))
          }else{
            callback()
          }
        } 
    }
    return {
      ruleForm:{
        username:'',
        pwd:''
      },
      rules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
          ],
          pwd:[
            {required:true,validator: validatePass}
          ]
      }
    }
  },
  methods: {
    submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            UserHttp.login(this.ruleForm).then(res=>{
                var {code,msg} = res.data
                if(code==200){
                    this.$message({
                        message:msg,
                        type:'success'
                    })
                    this.$router.push('/home')
                }else{
                    this.$message({
                        message:msg,
                        type:'error'
                    })
                }
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        })
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
  }
}
</script>

<style scoped>
.login{
    padding-top: 30px;
}
</style>